//
//  ThorUserCheckApi.m
//  ThorWebView_Example
//
//  Created by panfei mao on 2019/1/15.
//  Copyright © 2019 panfei mao. All rights reserved.
//

#import "ThorUserCheckApi.h"
#import <CommonCrypto/CommonDigest.h>

#define ThorKey @"linzi"

@interface ThorUserCheckApi ()

@property (nonatomic, copy) NSString *userPhone;
@property (nonatomic, copy) NSString *userId;
@property (nonatomic, copy) NSString *channel;

@end

@implementation ThorUserCheckApi

- (instancetype)initWithUserPhone:(NSString *)userPhone userId:(NSString *)userId channel:(NSString *)channel{
    self = [super init];
    if (self) {
        _userPhone = userPhone;
        _userId = userId;
        _channel = channel;
    }
    return self;
}

- (NSString * )requestUrl{
    return @"/api/user/unionlogin/usercheck";
}

- (id)requestArgument{

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:_channel forKey:@"channel"];
    [params setValue:_userPhone forKey:@"phone"];
    [params setValue:_userId forKey:@"thirdUserId"];
    
    NSMutableString *signStr = [NSMutableString string];
    NSArray *keyTemArray = [params allKeys];
    NSArray *keyArray = [keyTemArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSLiteralSearch];
    }];
    for (int i = 0 ;i < keyArray.count; i++) {
        id value = [params objectForKey:keyArray[i]];
        NSString *newValue =[NSString stringWithFormat:@"%@",value];
        [signStr appendString:newValue];
    }
    [signStr appendString:ThorKey];
    NSString *sign = [self MD5WithString:signStr];
    [params setValue:sign forKey:@"signInfo"];
    
    return params;
}

- (NSString *)MD5WithString:(NSString *)oldString {
    // Create pointer to the string as UTF8
    const char* ptr = [oldString UTF8String];
    unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
    
    // Create 16 byte MD5 hash value, store in buffer
    CC_MD5(ptr, (int)strlen(ptr), md5Buffer);
    
    // Convert MD5 value in the buffer to NSString of hex values
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x",md5Buffer[i]];
    }
    return output;
}

@end
